<template>
  <div>
    <Card dis-hover>
      <Form :label-width="100" :model="formData">
        <Row type="flex" style="flex-wrap: wrap">
          <FormItem label="分类：">
            <CategoryMultipleSelect
              slot="category"
              ref="categoryMultiple"
              @selectCategoryCallback="setFormCateUuids"
            />
          </FormItem>
          <FormItem label="SPU编码：">
            <Input
              v-model="formData.spuNo"
              placeholder="请输入SPU编码"
              style="width: 150px"
            ></Input>
          </FormItem>
          <FormItem label="商品名称：">
            <Input
              v-model="formData.productNameFinal"
              placeholder="请输入内容"
              style="width: 150px"
            />
          </FormItem>
          <FormItem label="商品品牌：">
            <Input
              v-model="formData.brandName"
              placeholder="请输入内容"
              style="width: 150px"
            />
          </FormItem>
          <FormItem label="商品类型：">
            <Select v-model="formData.productType" style="width: 150px">
              <Option
                v-for="(item, index) in productTypeList"
                :value="item.value"
                :key="index"
                >{{ item.label }}
              </Option>
            </Select>
          </FormItem>
        </Row>
        <Row style="padding-bottom: 16px" justify="end" type="flex">
          <Button
            v-if="showBtn('查询')"
            type="primary"
            @click="queryTableBt('1')"
            >查询</Button
          >
          <Button style="margin-left: 20px" @click="queryTableBt('0')"
            >清空</Button
          >
        </Row>
      </Form>
      <Row class="format_table_wrap">
        <el-row type="flex">
          <el-button
            v-show="showBtn('导出')"
            type="primary"
            :loading="exportLoading"
            @click="exportTable"
          >导出</el-button>
          <el-button
            v-show="showBtn('批量导入分销商品')"
            type="primary"
            @click="handleBatchImport"
          >批量导入分销商品</el-button>
        </el-row>
        <Table
          style="margin-top: 10px;"
          :columns="columns"
          :data="baseTableData"
          :loading="loading"
          height='500'
          @on-select="handleBaseTablaeSelect"
          @on-select-all="handleSelectAll"
          @on-select-all-cancel="handleSelectAllCancel"
        >
          <template slot-scope="{ row }" slot="action">
            <a v-if="showBtn('修改')" @click="toEdit(row)">修改</a>
            <a @click="toView(row)" style="margin-left: 5px">查看</a>
            <a
              v-if="showBtn('图文编辑')"
              @click="handleToGraphicPage(row)"
              style="margin-right: 5px; margin-left: 5px"
              >图文</a
            >
          </template>
        </Table>
        <div class="ivu-mt ivu-text-center">
          <Page
            transfer
            :total="totalNum"
            show-total
            show-sizer
            :current.sync="nowPage"
            @on-change="initData"
            @on-page-size-change="handleChangePage"
          />
        </div>
      </Row>
    </Card>
    <Modal v-model="modal2" title="选择修改信息模板" @on-ok="addModelOkFun()">
      <RadioGroup v-model="myModel" vertical>
        <Radio label="1">
          <span>基本信息模板 （根据SPU维护基本信息）</span>
        </Radio>
        <Radio label="2">
          <span>管理信息模板 （根据SPU维护管理信息）</span>
        </Radio>
        <Radio label="3">
          <span>SKU信息模板 （根据SKU维护包装信息）</span>
        </Radio>
      </RadioGroup>
    </Modal>
    <!--  -->
    <BatchImportDialog
      :visible.sync="batchImport.visible"
      :dialogTitle="batchImport.dialogTitle"
      :contents="batchImport.contents"
      :actionUrl="batchImport.actionUrl"
    ></BatchImportDialog>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import { handleOpenNewPage } from '@/utils/bizUtils'
import BatchImportDialog from '@/components/BatchImportDialog';
import CategoryMultipleSelect from '@/components/Category/MultipleSelect';
import { PRODUCT_TYPE_OPTIONS } from '@/constants/commodity';
export default {
  components: { BatchImportDialog, CategoryMultipleSelect },
  data () {
    return {
      batchImport: {
        visible: false,
        dialogTitle: '批量导入分销商品',
        contents: [
          '线下整理好需导入的表格。',
          '表格格式：SPU编码、是否分销（1为启用、2为取消）。',
          '导入表格从第二行开始导入，第一行为表头不导入。',
          '当导入的商品SPU编码错误，则不进行导入，即导入不成功。',
          '提交后页面关闭，系统后台更新数据，根据数据量大小更新时间不同。',
          '每次导入的限制为5万。',
        ],
        actionUrl: '/sysback/productManagementAttrinfo/batchUpdateSalePlatDist'
      },
      loading: false,
      exportLoading: false,
      modal2: false,
      myModel: '1',
      productUuid: '',
      skuNo: '',
      recordNo: '',
      uuid: '',
      isSaleMultiUnit: '',
      formData: {
        productAddState: '',
        categoryUuids: [],
        spuNo: '',
        skuNo: '',
        productNameFinal: '',
        productType: '',
        brandName: ''
      },
      totalNum: 0,
      pageShow: 10,
      nowPage: 1,
      isSearch: false,
      stateList: [
        {
          value: 'PREPARING',
          label: '待准入'
        },
        {
          value: 'FINISH',
          label: '已准入'
        }
      ],
      productTypeList: PRODUCT_TYPE_OPTIONS,
      columns: [
        {
          title: '商品状态',
          key: 'productAddStateStr',
          fixed: 'left',
          minWidth: 120
        },
        {
          title: '分类',
          key: 'categoryPath',
          minWidth: 160
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          minWidth: 160
        },
        {
          title: '创建人',
          key: 'createOperName',
          minWidth: 160
        },
        {
          title: '商品名称',
          key: 'productNameFinal',
          align: 'center',
          minWidth: 120
        },
        {
          title: '商品类型',
          key: 'productTypeStr',
          align: 'center',
          minWidth: 120
        },
        {
          title: '品牌',
          key: 'brandName',
          align: 'center',
          minWidth: 120
        },
        {
          title: '下属SKU数',
          key: 'skuCount',
          align: 'center',
          minWidth: 120
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 140
        }
      ],
      baseTableData: [],
      data2: [],
      name: '',
      nameList: [],
      uuidList: '',
      apiObj: {
        // 查询一级分类
        getLevelOneCategoryList: {
          url: '/sysback/choose/category/getLevelOneCategoryList', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 根据父分类查询子分类
        getByParentUuid: {
          url: '/sysback/choose/category/getByParentUuid', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 获取spu列表数据
        getTableList: {
          url: '/sysback/finish/spu/mgr/getSpuList', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 查询设置列
        getAllAttrInfoList: {
          url: '/sysback/finish/spu/mgr/getAllAttrInfoList', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 导出
        exportSpuGet: {
          url: '/sysback/finish/spu/mgr/exportSpuGet', // 接口地址
          type: 'get' // 接口请求类型
        }
      },
      nowTime: ''
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  created () {
    this.initData();
  },
  mounted () {},
  methods: {
    // 获取品类集合
    setFormCateUuids (list) {
      this.formData.categoryUuids = list.map(item => item.categoryUuid)
    },
    handleBatchImport () {
      this.batchImport.visible = true;
    },
    handleToGraphicPage (row) {
      handleOpenNewPage(this, {
        path:
          '/commodity/commodityManage/chageFromManage/chageFromManageImageText',
        query: { productUuid: row.uuid, productName: row.productNameFinal, spuNo: row.spuNo, fromType: 'single' }
      });
    },
    // 初始化数据
    initData () {
      let searchParam = [];
      searchParam.push({
        name: 'productAddState',
        value: this.formData.productAddState
      });
      searchParam.push({ name: 'productAddState_q', value: 'EQ' });
      searchParam.push({
        name: 'categoryPath',
        value: this.formData.categoryPath
      });
      searchParam.push({ name: 'categoryPath_q', value: 'Like' });
      searchParam.push({
        name: 'categoryUuid',
        value: this.formData.categoryUuid
      });
      searchParam.push({ name: 'categoryUuid_q', value: 'Like' });
      searchParam.push({ name: 'spuNo', value: this.formData.spuNo });
      searchParam.push({ name: 'spuNo_q', value: 'EQ' });
      searchParam.push({
        name: 'productNameFinal',
        value: this.formData.productNameFinal
      });
      searchParam.push({ name: 'productNameFinal_q', value: 'Like' });
      searchParam.push({
        name: 'productType',
        value: this.formData.productType
      });
      searchParam.push({ name: 'productType_q', value: 'EQ' });
      searchParam.push({ name: 'brandName', value: this.formData.brandName });
      searchParam.push({ name: 'brandName_q', value: 'Like' });
      let data = {
        nowPage: this.nowPage,
        pageShow: this.pageShow,
        searchParam: JSON.stringify(searchParam),
        sortName: '',
        sortType: ''
      };
      let curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.loading = true;
      // 开始请求列表
      ApiRequest(
        this.apiObj.getTableList.url,
        this.apiObj.getTableList.type,
        data
      ).then(res => {
        let rData = res;
        if (rData.retData !== '') {
          rData.retData = rData.retData;
        }
        if (
          rData.retData.results !== null &&
          rData.retData.results.length > 0
        ) {
          this.baseTableData = rData.retData.results;
        } else {
          this.baseTableData = [];
        }

        this.totalNum = rData.retData.totalNum;
        this.loading = false;
      });
    },
    // 选择分类
    selctCategory () {
      this.onSearchClassifyModal = true;
      this.menuData1 = [];
      this.menuData2 = [];
      this.menuData3 = [];
      this.menuData4 = [];
      this.getTime();
    },
    // 编辑
    toEdit (row) {
      let curBtnId = getBtnsId('修改');
      sessionStorage.setItem('buttonId', curBtnId);
      this.productUuid = row.uuid;
      this.recordNo = row.recordNo;
      this.skuNo = row.skuNo;
      this.isSaleMultiUnit = row.isSaleMultiUnit;
      let data = {
        spuNo: row.spuNo
      };
      ApiRequest(
        '/sysback/spu/query/checkPerm?spuNo=' + row.spuNo,
        'post',
        data,
        false
      ).then(res => {
        if (res.retData === 'ok') {
          this.modal2 = true;
        }
      });
    },
    toView (row) {
      handleOpenNewPage(this, {
        path: '/commodity/commodityManage/SPUManage/SPUManageDetail',
        query: { productUuid: row.uuid, orderType: row.orderType, spuNo: row.spuNo }
      });
    },
    // 查询/清空
    queryTableBt (type) {
      if (type === '0') {
        this.isSearch = false;
        this.formData.productAddState = '';
        this.formData.spuNo = '';
        this.formData.skuNo = '';
        this.formData.productType = '';
        this.formData.brandName = '';
        this.formData.categoryUuids = [];
        this.formData.productNameFinal = '';
        this.allPathName = '';
      }
      if (this.formData.categoryUuid !== '') {
        this.isSearch = true;
      }
      this.nowPage = 1;
      this.initData();
    },
    // 导出表格
    exportTable () {
      const {
        categoryUuid,
        brandName,
        productNameFinal,
        spuNo,
        productType
      } = this.formData;
      if (
        !this.uuidList &&
        this.nameList.length === 0 &&
        !categoryUuid.trim() &&
        !brandName.trim() &&
        !productNameFinal.trim() &&
        !spuNo.trim() &&
        !productType
      ) {
        return this.$Message.error('请至少输入一个筛选项');
      }
      let curBtnId = getBtnsId('导出');
      sessionStorage.setItem('buttonId', curBtnId);
      window.location.href =
        this.exportBaseURL +
        '/sysback/finish/spu/mgr/exportSpuGet?categoryUuid=' +
        this.formData.categoryUuid +
        '&brandName=' +
        this.formData.brandName +
        '&nameList=' +
        this.nameList.join(',') +
        '&productName=' +
        this.formData.productNameFinal +
        '&spuNo=' +
        this.formData.spuNo +
        '&uuidList=' +
        this.uuidList +
        '&productType=' +
        this.formData.productType;
    },
    addModelOkFun () {
      switch (this.myModel) {
        case '1': // 基本信息模板
          handleOpenNewPage(this, {
            name: 'chageFromManageBaseEdit',
            query: { uuid: this.productUuid, type: 'single_spu' }
          });
          break;
        case '2': // 管理信息模板
          handleOpenNewPage(this, {
            name: 'chageFromManageInfoEdit',
            query: { uuid: this.productUuid, type: 'single_spu' }
          });
          break;
        case '3': // SKU信息模板
          handleOpenNewPage(this, {
            name: 'chageFromManageSKUEdit',
            query: { uuid: this.productUuid, type: 'single_spu' }
          });
          break;
        case '4': // 供货信息模板
          handleOpenNewPage(this, {
            path:
              '/commodity/commodityInfoUpdate/chageFromManage/chageFromManageSupplyInfo',
            query: { uuid: this.productUuid, fromType: 'single' }
          });
          break;
        case '5': // 供货参照城市
          if (this.isSaleMultiUnit === '1') {
            // 是钢材
            handleOpenNewPage(this, {
              path:
                '/commodity/commodityManage/chageFromManage/chageFromManageTemplateCitySteel',
              query: { uuid: this.productUuid, fromType: 'single' }
            });
          } else {
            handleOpenNewPage(this, {
              path:
                '/commodity/commodityManage/chageFromManage/chageFromManageTemplateCity',
              query: { uuid: this.productUuid, fromType: 'single' }
            });
          }
          break;
        case '6': // 供货进价信息
          if (this.isSaleMultiUnit === '1') {
            // 是钢材
            handleOpenNewPage(this, {
              path:
                '/commodity/commodityManage/chageFromManage/chageFromManageenterPriceSteel',
              query: { uuid: this.productUuid, fromType: 'single' }
            });
          } else {
            handleOpenNewPage(this, {
              path:
                '/commodity/commodityManage/chageFromManage/chageFromManageenterPrice',
              query: { uuid: this.productUuid, fromType: 'single' }
            });
          }
          break;
        case '10': // 修改图文信息
          handleOpenNewPage(this, {
            path:
              '/commodity/commodityManage/chageFromManage/chageFromManageImageText',
            query: { productUuid: this.productUuid, fromType: 'single' }
          });
          break;
      }
    },
    handleSelect (row) {
      this.nameList = [];
      row.forEach(element => {
        this.nameList.push(element.type + '-' + element.name);
      });
    },
    // 全选
    handleSelectAll (row) {
      this.uuidList = '';
      row.forEach(element => {
        this.uuidList += element.uuid + ',';
      });
    },
    // 取消全选
    handleSelectAllCancel () {
      this.uuidList = '';
    },
    // 基础列表勾选事件
    handleBaseTablaeSelect (row) {
      this.uuidList = '';
      row.forEach(element => {
        this.uuidList += element.uuid + ',';
      });
    },
    handleChangePage (val) {
      this.pageShow = val;
      this.$nextTick(() => {
        this.initData();
      });
    }
  }
};
</script>
<style>
.ivu-table-wrapper {
  overflow: visible;
}
</style>
